package com.letcoding.spiderAutoHome.config;

import com.letcoding.spiderAutoHome.job.CloseHttpConnectionJob;
import com.letcoding.spiderAutoHome.job.CrawlerAutoHomeJob;
import org.quartz.CronTrigger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class QuartzConfig {
    /**
     * 定义关闭无效连接任务
     */
    @Bean
    public JobDetailFactoryBean closeHttpConnectionJob() {
        JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean ();
        jobDetailFactoryBean.setApplicationContextJobDataKey ("context");
        jobDetailFactoryBean.setJobClass (CloseHttpConnectionJob.class);
        jobDetailFactoryBean.setDurability (true);
        return jobDetailFactoryBean;
    }

    /**
     * 定义关闭无效连接触发器
     *
     * @Qualifier起到了一个筛选的作用只有Bean上加有@Qualifier注解的Bean才会被收集注入。
     */
    @Bean("closeHttpConnectionJobTrigger")
    public CronTriggerFactoryBean closeHttpConnectionJobTrigger(@Qualifier(value = "closeHttpConnectionJob") JobDetailFactoryBean itemJobBean) {
        CronTriggerFactoryBean trigger = new CronTriggerFactoryBean ();
        trigger.setJobDetail (itemJobBean.getObject ());
        trigger.setCronExpression ("0/5 * * * * ? ");
        return trigger;
    }

    /**
     * 定义调度器
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(CronTrigger[] cronTriggerImpl) {
        SchedulerFactoryBean bean = new SchedulerFactoryBean ();
        bean.setTriggers (cronTriggerImpl);
        return bean;
    }

    /**
     * 定义定时爬取评测任务任务
     */
    @Bean("crawlerAutoHomeJob")
    public JobDetailFactoryBean crawlerAutoHomeJob() {
        JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean ();
        jobDetailFactoryBean.setApplicationContextJobDataKey ("context");
        jobDetailFactoryBean.setJobClass (CrawlerAutoHomeJob.class);
        jobDetailFactoryBean.setDurability (true);

        return jobDetailFactoryBean;
    }

    /**
     * 定义关闭无效连接触发器
     */
    @Bean("crawlerAutoHomeJobTrigger")
    public CronTriggerFactoryBean crawlerAutoHomeJobTrigger(
            @Qualifier(value = "crawlerAutoHomeJob") JobDetailFactoryBean itemJobBean) {
        CronTriggerFactoryBean tigger = new CronTriggerFactoryBean ();
        tigger.setJobDetail (itemJobBean.getObject ());
        tigger.setCronExpression ("0/5 * * * * ? ");
        return tigger;
    }
}
